<template>
  <div class="rule-config feature-out">
    <div ref="searchDiv">
      <div class="filter-container">
        <el-input
          v-model="tableQuery.search.ruleCode"
          clearable
          style="width: 200px;"
          placeholder="规则编码"
          size="small"
          class="filter-item"
        ></el-input>
        <el-input
          v-model="tableQuery.search.ruleName"
          clearable
          style="width: 200px;"
          placeholder="规则名称"
          size="small"
          class="filter-item"
        ></el-input>
        <el-select
          size="small"
          v-model="tableQuery.search.ruleType"
          clearable
          placeholder="请选择规则类型"
          style="width: 200px;"
          class="filter-item"
        >
          <el-option
            v-for="item in ruleTypeOptions"
            :key="item.ruleType"
            :label="item.type_name"
            :value="item.ruleType"
          ></el-option>
        </el-select>
        <el-button
          size="small"
          @click="handleFilter"
          type="primary"
          ref="btnQuery"
          class="filter-item"
        >
          查询
        </el-button>
        <el-button
          @click="handleReset"
          size="small"
          type="primary"
          ref="btnRefresh"
          class="filter-item"
        >
          重置
        </el-button>
      </div>
      <div style="margin-bottom:12px;display:flex;justify-content: flex-end;">
        <el-button size="small" @click="ruleUpload('true')" type="primary">
          规则导入
        </el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="tableLoading"
      :show-overflow-tooltip="true"
      style="width: 100%;margin-bottom: 12px;"
      :max-height="tableHeight"
    >
      <el-table-column
        label="规则编码"
        prop="ruleCode"
        align="center"
        width="160px"
      ></el-table-column>
      <el-table-column
        label="规则名称"
        prop="ruleName"
        align="center"
        min-width="300px"
      ></el-table-column>
      <el-table-column
        label="规则类型"
        prop="ruleType"
        min-width="100px"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="200px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="mini"
            @click="handlePop('update', scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="tableQuery.page"
        :page-sizes="[10, 20, 50]"
        :page-size="tableQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="actionType === 'add' ? '新增' : '修改'"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :visible.sync="formVisible"
      width="370px"
    >
      <el-form
        ref="ruleForm"
        class="small-space"
        label-position="right"
        label-width="80px"
        :model="createdItem"
        :rules="rules"
        style="width: 90%; margin-left:0px;"
      >
        <el-form-item prop="ruleName" label="规则名称">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.ruleName"
            placeholder="请输入规则名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="ruleType" label="规则类型">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.ruleType"
            placeholder="请输入规则类型"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="formVisible = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="规则导入"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :visible.sync="upload"
      width="476px"
    >
      <el-form label-width="100px">
        <el-form-item label="规则文件:">
          <el-upload
            ref="upload"
            :action="uploadURL"
            :show-file-list="true"
            :multiple="false"
            :auto-upload="false"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :accept="fileTypes"
            :on-change="uploadChange"
            :on-remove="handleRemove"
          >
            <el-button size="mini">
              <i class="el-icon-upload2"></i>
              点击上传
            </el-button>
            <div class="el-upload__tip" slot="tip">
              只能上传Excel文件! 点击下载
              <el-button @click="download" type="text" size="mini">
                示例文件
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="ruleUpload('false')">取消</el-button>
        <el-button size="mini" type="primary" @click="submitUpload">
          导入
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
// 具体用法查看官方API:https://github.com/kaorun343/vue-property-decorator
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import TitleContainer from '@/components/title/TitleContainer.vue'
import { Form, Table, Upload } from 'element-ui'
import {
  getConfigList,
  deleteConfig,
  getConfighis,
  getTypemap,
  update,
  uploadURL,
  downloadURL
} from '@/api/risksystem/strategy/ruleConfig'
const defaultPage = {
  limit: 10,
  page: 1
}
const defaultQuery = {
  search: {
    ruleCode: '',
    ruleName: '',
    ruleType: ''
  }
}
const defaultCreateQuery = {
  ruleName: '',
  rule_alias: '',
  ruleType: '',
  status: ''
}
@Component({
  name: 'ruleConfig',
  components: {
    //引用的组件在这里声明
    TitleContainer
  }
})
export default class extends Vue {
  private ruleTypeOptions = []
  private tableQuery: any = Object.assign({}, defaultQuery, defaultPage)
  private total = 0
  private tableData = []
  private tableHeight: any = null
  private tableLoading = true

  private createdItem = Object.assign({}, defaultCreateQuery)
  private actionType = 'add'
  private formVisible = false
  private formSubmiting = false
  private formHisVisible = false
  private rules: any = {
    ruleName: [{ required: true, message: '请填写规则名称', trigger: 'blur' }],
    ruleType: [{ required: true, message: '请填写规则类型', trigger: 'blur' }]
  }
  private upload = false
  private refsList = {
    projectName: '',
    ruleFilePath: '',
    ruleHistorys: []
  }
  // 文件上传
  get uploadURL() {
    return uploadURL
  }
  // 文件下载
  get downloadURL() {
    return downloadURL
  }
  private fileList: any[] = []
  private files = {}
  private fileName = ''
  private requestHeader = {
    'Content-Type': 'multipart/form-data'
    // 'X-TOKEN': localStorage.getItem('x-token')
  }
  private fileTypes = '.xls,.xlsx' //上传文件类型

  mounted() {
    this.getTypeMap()
    this.getList()
    this.init()
  }
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  }
  // 表格高度
  private init() {
    var _this = this
    this.$nextTick(() => {
      this.tableHeight =
        window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 240
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 240
      })
    }
  }
  // 数据源
  private async getTypeMap() {
    const { data } = await getTypemap()
    this.ruleTypeOptions = data.rows
  }
  // 表格内容
  private async getList() {
    this.tableLoading = true
    const data: any = await getConfigList(this.tableQuery)
    if (data.code === 0) {
      this.tableLoading = false
      this.tableData = data.data.rows
      this.total = Number(data.data.total)
    }
  }
  // 分页部分
  private handleFilter() {
    this.tableQuery.page = 1
    this.getList()
  }
  private handleReset() {
    this.tableQuery = {
      search: {
        ruleCode: '',
        ruleName: '',
        ruleType: ''
      }
    }
    this.getList()
  }
  private handleSizeChange(val: any) {
    this.tableQuery.limit = val
    this.getList()
  }
  private handleCurrentChange(val: any) {
    this.tableQuery.page = val
    this.getList()
  }
  // 修改
  private async update(val: any) {
    const data: any = await update(val)
    if (data.code === 0) {
      this.getList()
      this.getTypeMap()
      this.formVisible = false
      this.$message.success('修改成功！')
    }
  }
  // 新增|编辑
  private handlePop(action: any, data = {}) {
    if (action === 'add') {
      this.createdItem = Object.assign({}, defaultCreateQuery)
    }
    if (action === 'update') {
      Object.assign(this.createdItem, data, {
        // ruleType: +data.ruleType
      })
    }
    this.actionType = action
    this.formVisible = true
    this.$nextTick(() => {
      ;(this.$refs['ruleForm'] as Form).clearValidate()
    })
  }

  // 删除
  private async delete(id: any) {
    const data: any = await deleteConfig({ id: id })
    if (data.code === 0) {
      this.$message({ type: 'success', message: '删除成功!' })
      this.getList()
    } else {
      this.$message.error('删除失败')
    }
  }
  private handleDelete(id: any) {
    this.$confirm('确认删除该条规则配置？').then(() => {
      this.delete(id)
    })
    this.$confirm('确认删除该条规则配置？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        this.delete(id)
      })
      .catch(() => {})
  }
  // 上传
  private ruleUpload(val: any) {
    this.upload = val === 'true' ? true : false
    this.$nextTick(() => {
      ;(this.$refs['upload'] as Upload).clearFiles()
    })
  }
  private submitUpload() {
    if (this.fileList.length === 0) {
      this.$message.error('请选择上传文件！')
    }
    ;(this.$refs['upload'] as Upload).submit()
  }
  private uploadChange(file: any, fileList: any) {
    this.fileList = [fileList[fileList.length - 1]]
  }
  private handleRemove(file: any, fileList: any) {
    this.fileList = fileList
  }
  private uploadSuccess(res: any) {
    if (res.code === 0) {
      this.$message.success('上传成功！')
      this.files = []
      this.fileList = []
      this.getList()
      this.upload = false
    } else {
      this.$message.error('上传失败！')
      this.files = []
      this.fileList = []
      this.getList()
    }
  }
  // 保存
  private save() {
    ;(this.$refs['ruleForm'] as Form).validate(async valid => {
      if (valid) {
        let action = this.actionType
        let data = this.createdItem
        this.update(data)
      }
    })
  }
  private async handlePopHis(id: any) {
    this.formHisVisible = true
    const { data } = await getConfighis({ id: id })
    if (data.rows.length === 0) {
      this.refsList
    } else {
      this.refsList = data.rows[0]
    }
  }
  private download() {
    window.location.href = this.downloadURL
  }
}
</script>
<style scoped>
.rule-config {
  padding: 20px;
}
.table-container {
  margin-bottom: 20px;
}
</style>
